package com.leqicheng.tenon;

import java.io.File;
import java.net.URL;
import java.net.URLConnection;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.widget.Toast;

import com.leqicheng.tenon.updata.FileDownloadThread;
import com.leqicheng.tenon.util.BottomDialog;
import com.leqicheng.tenon.util.BottomDialog.OnBottomDialogListener;

public class UpdataApk {

    private Context mContext;
    private static String BASE_FILENAME = "Tenon";
    private int mFileSize = 0;
    private int mDownloadedSize = 0;
    public File mFile;

    public UpdataApk(Context mContext, String updataVersion, String updataApkUrl) {
        super();
        this.mContext = mContext;
        showUpdateTips(updataVersion, updataApkUrl);
    }

    @SuppressLint("HandlerLeak")
    Handler downloadhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 当收到更新视图消息时，计算已完成下载百分比，同时更新进度条信息
            int progress = (Double
                    .valueOf((mDownloadedSize * 1.0 / mFileSize * 100)))
                    .intValue();
            if (progress == 100) {
                openFile(mFile);
            }
        }

    };

    private void showUpdateTips(final String updataVersion,
            final String updataApkUrl) {
        BottomDialog NewVersionTips = new BottomDialog(mContext,
                R.style.bottom_dialog, new OnBottomDialogListener() {

                    @Override
                    public void back(int mButtonNumber) {
                        if (mButtonNumber == 2) {
                            String fileName = BASE_FILENAME + updataVersion
                                    + ".apk";
                            download(updataApkUrl, fileName);
                        } else if (mButtonNumber == 1) {

                        }
                    }
                });
        Window win = NewVersionTips.getWindow();
        win.setGravity(Gravity.BOTTOM);
        NewVersionTips.setCanceledOnTouchOutside(true);
        NewVersionTips.requestWindowFeature(Window.FEATURE_NO_TITLE);
        NewVersionTips.init("游戏环境发现最新版本", "现在更新");
        NewVersionTips.show();
        win.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    private void download(String downloadUrl, String downloadFileName) {
        // 获取SD卡目录
        String dowloadDir = Environment.getExternalStorageDirectory()
                + "/tenon_runtime/";
        File file = new File(dowloadDir);
        // 创建下载目录
        if (!file.exists()) {
            file.mkdirs();
        }

        // 读取下载线程数，如果为空，则单线程下载
        int downloadTN = 1;
        // 如果下载文件名为空则获取Url尾为文件名
        int fileNameStart = downloadUrl.lastIndexOf("/");
        String fileName = "".equals(downloadFileName) ? downloadUrl
                .substring(fileNameStart) : downloadFileName;
        // 开始下载前把下载按钮设置为不可用
        // 进度条设为0
        // downloadProgressBar.setProgress(0);
        // 启动文件下载线程
        if (fileIsExists(dowloadDir + fileName)) {
            // downloadProgressBar.setProgress(100);
            // progressMessage.setText("榫游戏环境已经下载完毕。");
            File tenonFile = new File(dowloadDir + fileName);
            openFile(tenonFile);
            return;
        }
        new downloadTask(downloadUrl, Integer.valueOf(downloadTN), dowloadDir
                + fileName).start();

    }

    // 判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * @author ideasandroid
     *         主下载线程
     */
    public class downloadTask extends Thread {
        private int blockSize, downloadSizeMore;
        private int threadNum = 5;
        String urlStr, threadNo, fileName;

        public downloadTask(String urlStr, int threadNum, String fileName) {
            Toast.makeText(mContext, "正在下载游戏运行环境", Toast.LENGTH_LONG).show();
            Toast.makeText(mContext, "安装完成后请手动打开游戏", Toast.LENGTH_LONG).show();
            this.urlStr = urlStr;
            this.threadNum = threadNum;
            this.fileName = fileName;
        }

        @Override
        public void run() {
            FileDownloadThread[] fds = new FileDownloadThread[threadNum];
            try {
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                // 获取下载文件的总大小
                mFileSize = conn.getContentLength();
                // 计算每个线程要下载的数据量
                blockSize = mFileSize / threadNum;
                // 解决整除后百分比计算误差
                downloadSizeMore = (mFileSize % threadNum);
                mFile = new File(fileName);
                for (int i = 0; i < threadNum; i++) {
                    // 启动线程，分别下载自己需要下载的部分
                    FileDownloadThread fdt = new FileDownloadThread(url, mFile,
                            i * blockSize, (i + 1) * blockSize - 1);
                    fdt.setName("Thread" + i);
                    fdt.start();
                    fds[i] = fdt;
                }
                boolean finished = false;
                while (!finished) {
                    // 先把整除的余数搞定
                    mDownloadedSize = downloadSizeMore;
                    finished = true;
                    for (int i = 0; i < fds.length; i++) {
                        mDownloadedSize += fds[i].getDownloadSize();
                        if (!fds[i].isFinished()) {
                            finished = false;
                        }
                    }
                    // 通知handler去更新视图组件
                    downloadhandler.sendEmptyMessage(0);
                    // 休息1秒后再读取下载进度
                    sleep(500);
                }
            } catch (Exception e) {
            }
        }
    }

    private void openFile(File file) {
        SharedPreferences preferences1 = mContext.getSharedPreferences("11",
                0x0001);
        Editor editor = preferences1.edit();
        if (preferences1.getInt("num", 0) != 0) {
            editor.putInt("num", 0);
            editor.commit();
        }
        Log.i("OpenFile", file.getName());
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
